using Microsoft.Extensions.Logging;
using SumerCoreDevOps.ExecuteNodeApi.Services;
using SumerCoreDevOps.Infrastructure.Libraries;
using SumerCoreDevOps.Infrastructure.Security;
using SumerCoreDevOps.Shared.Models.Messages;
using System.Text.Json;

namespace SumerCoreDevOps.ExecuteNodeApi.Handlers;

/// <summary>
/// Git 克隆处理器
/// </summary>
public class GitCloneHandler : IStepHandler
{
    private readonly ILogger<GitCloneHandler> _logger;
    private readonly GitLibrary _gitLibrary;
    private readonly TaskExecutor _taskExecutor;

    public GitCloneHandler(
        ILogger<GitCloneHandler> logger,
        GitLibrary gitLibrary,
        TaskExecutor taskExecutor)
    {
        _logger = logger;
        _gitLibrary = gitLibrary;
        _taskExecutor = taskExecutor;
    }

    public async Task<StepExecutionResult> ExecuteAsync(WorkflowStepDispatchMessage message)
    {
        try
        {
            // 解析步骤配置
            var config = JsonSerializer.Deserialize<GitCloneConfig>(message.StepConfig);

            if (config == null || string.IsNullOrEmpty(config.Repository))
            {
                return new StepExecutionResult
                {
                    Success = false,
                    ErrorMessage = "Git 仓库地址未配置"
                };
            }

            // 获取 Git 凭证
            string? username = null;
            string? password = null;

            if (message.EncryptedCredentials.TryGetValue(Shared.Enums.CredentialType.Git, out var encryptedCred))
            {
                try
                {
                    // 解密凭证
                    var decryptedJson = EncryptionHelper.Decrypt(encryptedCred);
                    var gitCredential = JsonSerializer.Deserialize<GitCredential>(decryptedJson);

                    if (gitCredential != null)
                    {
                        username = gitCredential.Username;
                        // 优先使用 Token，如果没有则使用密码
                        password = gitCredential.Token ?? gitCredential.Password;

                        _logger.LogInformation("Git 凭证解密成功，用户名: {Username}", username);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, "Git 凭证解密失败，将尝试匿名访问");
                }
            }

            // 订阅 Git 日志事件，转发到控制面板
            _gitLibrary.OnLog += async (logMessage, logLevel) =>
            {
                await _taskExecutor.SendLogAsync(message.TaskId, message.StepId, logMessage, logLevel);
            };

            bool success;
            string? selectedTag = null;
            string? createdBranch = null;

            // 判断是否使用 Tag 模式
            if (!string.IsNullOrEmpty(config.TagPattern))
            {
                // Tag 模式：根据模式查找并 checkout tag，或从 tag 创建分支
                await _taskExecutor.SendLogAsync(message.TaskId, message.StepId,
                    $"🏷️ 使用 Tag 模式: {config.TagPattern}");

                var (tagSuccess, tagName, branchName) = await _gitLibrary.CloneWithTagAsync(
                    config.Repository,
                    message.WorkDirectory,
                    config.TagPattern,
                    config.CreateBranchFromTag,
                    config.BranchNameTemplate,
                    username,
                    password);

                success = tagSuccess;
                selectedTag = tagName;
                createdBranch = branchName;

                if (success && selectedTag != null)
                {
                    var modeMsg = config.CreateBranchFromTag
                        ? $"✓ 从标签 '{selectedTag}' 创建分支 '{createdBranch}'"
                        : $"✓ 已切换到标签 '{selectedTag}'";
                    await _taskExecutor.SendLogAsync(message.TaskId, message.StepId, modeMsg);
                }
            }
            else
            {
                // 普通模式：克隆指定分支
                success = await _gitLibrary.CloneRepositoryAsync(
                    config.Repository,
                    message.WorkDirectory,
                    config.Branch,
                    username,
                    password);
            }

            if (success)
            {
                // 获取提交信息
                var commitInfo = await _gitLibrary.GetLatestCommitAsync(message.WorkDirectory);

                var outputContext = new Dictionary<string, string>
                {
                    ["GIT_REPOSITORY"] = config.Repository,
                    ["GIT_BRANCH"] = createdBranch ?? config.Branch ?? "main",
                    ["WORK_DIRECTORY"] = message.WorkDirectory
                };

                if (selectedTag != null)
                {
                    outputContext["GIT_TAG"] = selectedTag;
                    if (createdBranch != null)
                    {
                        outputContext["GIT_BRANCH_FROM_TAG"] = createdBranch;
                    }
                }

                if (commitInfo != null)
                {
                    outputContext["GIT_COMMIT_HASH"] = commitInfo.Hash;
                    outputContext["GIT_COMMIT_MESSAGE"] = commitInfo.Message;
                    outputContext["GIT_AUTHOR"] = commitInfo.Author;
                }

                return new StepExecutionResult
                {
                    Success = true,
                    Progress = 100,
                    OutputContext = outputContext
                };
            }
            else
            {
                return new StepExecutionResult
                {
                    Success = false,
                    ErrorMessage = "Git 克隆失败"
                };
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Git 克隆处理器执行失败");
            return new StepExecutionResult
            {
                Success = false,
                ErrorMessage = ex.Message
            };
        }
    }
}

public class GitCloneConfig
{
    /// <summary>
    /// 仓库地址
    /// </summary>
    public string Repository { get; set; } = null!;

    /// <summary>
    /// 分支名称（与 TagPattern 二选一）
    /// </summary>
    public string? Branch { get; set; }

    /// <summary>
    /// Tag 模式（支持通配符，如 v*.*.* 或 release-*）
    /// 如果指定，将查找匹配的最新 tag
    /// </summary>
    public string? TagPattern { get; set; }

    /// <summary>
    /// 是否从 Tag 创建分支（默认 false，直接 checkout tag）
    /// </summary>
    public bool CreateBranchFromTag { get; set; } = false;

    /// <summary>
    /// 分支名称模板（仅当 CreateBranchFromTag=true 时有效）
    /// 支持占位符 {tag}，如 "release/{tag}"
    /// 默认: "branch-from-{tag}"
    /// </summary>
    public string? BranchNameTemplate { get; set; }
}
